package demo;

import java.io.InputStream;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;


@ManagedBean(name="fileDownloadController")
@ViewScoped
public class FileDownloadController {

	private StreamedContent file;
	
	private StreamedContent file1;
	
	private StreamedContent file2;
	
	private StreamedContent file3;
	
	public FileDownloadController() {
		
		System.out.println("FileDownloadController bean创建了");
		
		/*
		 * 注意，第一种情况，第二种情况，第三种情况都是从根路径下下载
		 */
		String name = "/resource_files/myword.doc";
		InputStream stream =  FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(name);
		file = new DefaultStreamedContent(stream, "application/doc",
		"downloaded_word.doc");
		
		String name1 = "/resource_files/mypdf.pdf";
		InputStream stream1 =  FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(name1);
		file1 = new DefaultStreamedContent(stream1, "application/pdf",
		"downloaded_word.pdf");
		
		
		String name2 = "/resource_files/mytxt.txt";
		InputStream stream2 =  FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(name2);
		file2= new DefaultStreamedContent(stream2, "application/txt",
		"downloaded_word.txt");
		
		/*
		 * 注意，这种情况下是从类路径下下载
		 */
		String name3 = "car.png";
		/*
		 * 注意，此处this.getClass().getResourceAsStream(name3),是从当前类的路径下加载资源文件
		 */
		InputStream stream3 =  this.getClass().getResourceAsStream(name3);
		file3= new DefaultStreamedContent(stream3, "application/png",
		"downloaded_png.png");
	}
	
	public StreamedContent getFile() {
		return this.file;
	}

	public StreamedContent getFile1() {
		return file1;
	}

	public StreamedContent getFile2() {
		return file2;
	}

	public StreamedContent getFile3() {
		return file3;
	}
	
	
	
}
